from channels.generic.websocket import JsonWebsocketConsumer
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from mongolog.models import UserActivityLog
from mongolog.serializers import UserActivityLogSerializer


class UserActivityConsumer(JsonWebsocketConsumer):
    groups = ['user_activity']

    def connect(self):
        self.accept()

    def disconnect(self, code):
        pass

    def receive_json(self, content, **kwargs):
        # 推送10条最近的消息
        if content['request_type'] == 'refresh':
            queryset = reversed(UserActivityLog.objects.filter(abnormal=True).order_by('-log_time')[:10])
            for ins in queryset:
                serializer = UserActivityLogSerializer(instance=ins)
                self.send_json(serializer.data)

    def broadcast_activity(self, message):
        self.send_json(content=message['activity'])


def broadcast_user_activity(message):
    """广播推送用户行为监控消息"""
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        UserActivityConsumer.groups[0],
        {
            'type': 'broadcast.activity',
            'activity': message
        }
    )
